package com.gcd.gym.service.impl;

import com.gcd.gym.service.UploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Service
public class UploadServiceImpl implements UploadService {
    @Value("${upload.location}")
    private String uploadLocation;
    @Override
    public String uploadImage(MultipartFile file, String type) {
        //创建目录
        File dir=new File(uploadLocation+"/images/"+type);
        if(!dir.exists()) {
            boolean b=dir.mkdirs();
            if (!b) {
                throw new RuntimeException("级联目录创建异常");
            }
        }

        //给上传的文件起名
        LocalDateTime now=LocalDateTime.now();
        String fileName=now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Random random=new Random();
        int sid=random.nextInt(1000);
        fileName=fileName+"-"+sid;


        //拼扩展名
        String originalFileName=file.getOriginalFilename();
        int idx=originalFileName.lastIndexOf(".");
        String ext=originalFileName.substring(idx);
        fileName=fileName+ext;
        String fullName=dir.getAbsolutePath()+"/"+fileName;


        File target=new File(fullName);

        //存文件
        try {
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败");
        }

        //返回存储地址和访问地址

        return "/images/"+type+"/"+fileName;
    }
}
